package org.kugua.image.impl;

import lombok.extern.slf4j.Slf4j;
import org.kugua.common.Constants;
import org.kugua.image.ImageSelector;
import org.kugua.utils.ImageUtils;
import org.kugua.utils.RandomUtils;
import org.springframework.core.io.ClassPathResource;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.*;

/**
 * MemoryBgImageSelector
 *
 * @author Administrator
 * @create 2024/9/10 11:35
 * @since 1.0.0
 */
@Slf4j
public class MemoryBgImageSelector implements ImageSelector<BufferedImage> {

    private static final Map<String, BufferedImage> BUFFERED_IMAGE_HASH_MAP = new HashMap<>();

    private static final List<String> MAPS_KEYS = new ArrayList<>();

     static {
         try {
             ClassPathResource classPathResource = new ClassPathResource(Constants.Path.BACKGROUND_PATH);
             File file = classPathResource.getFile();
             if (!file.isDirectory()) {
                 log.error("background directory not exist in directory resources.");
                 throw new RuntimeException("background directory not exist in directory resources.");
             }
             File[] files = file.listFiles();
             if (Objects.nonNull(files)) {
                 for (File f : files) {
                     String fileName = f.getName().toUpperCase();
                     if (ImageUtils.isSupportType(fileName)) {
                         BUFFERED_IMAGE_HASH_MAP.put(fileName, ImageIO.read(f));
                         MAPS_KEYS.add(fileName);
                     }
                 }
             }
         } catch (Exception e) {
             throw new RuntimeException(e);
         }
     }

    /**
     * 选择Image
     *
     * @return BufferedImage
     */
    @Override
    public BufferedImage select() {
        int index = RandomUtils.random(MAPS_KEYS.size());
        String key = MAPS_KEYS.get(index);
        BufferedImage bufferedImage = BUFFERED_IMAGE_HASH_MAP.get(key);
        return copy(bufferedImage);
    }
}
